package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 判断用户访问的页面或其他资源时,是否过滤和是否登录
 * @author solang
 * @date 2022-12-19 10:31
 */
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器,支持通配符
    public static final AntPathMatcher PATH_MATCHER= new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1获取请求URl
        String requestURL=request.getRequestURI();
        //定义不需要过滤的请求RUL
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "user/sendMsg",//移动端发送短信
                "/user/login",//移动端登录,
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //2判断是否过滤
        boolean check = check(urls, requestURL);
        //3.符合urls要求不处理
        if(check){
            filterChain.doFilter(request,response);
            return;
        }
        //4-1.判断登录状态
        if(request.getSession().getAttribute("employee")!=null){
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            //获取线程id
//            long id = Thread.currentThread().getId();
//            log.info("线程Id"+id);
            //不为空则处于登录状态,放行
            filterChain.doFilter(request,response);
            return;
        }
        //4-2.判断登录状态
        if(request.getSession().getAttribute("user")!=null){

            User user = (User) request.getSession().getAttribute("user");
            Long id = user.getId();
            log.info("user:{}",user );
//            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(id);
            //获取线程id
//            long id = Thread.currentThread().getId();
//            log.info("线程Id"+id);
            //不为空则处于登录状态,放行
            filterChain.doFilter(request,response);
            return;
        }
        //5.未登录,返回NOTLOGIN让前端拦截器拦截,跳转到登录界面

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     *
     * @param urls
     * @param requestURL
     * @return
     */
    private boolean check(String[] urls, String requestURL) {
        for (String url: urls) {
            boolean match = PATH_MATCHER.match(url, requestURL);
            if(match){
                return true;
            }
        }
        return false;
    }
}
